from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *

from ui.Ui_public_script_manager_widget import Ui_widget_public_scripts_manager
from app.window.msg_box import Msg_box
from app.window.public_script_editor_dialog import Public_script_editor_dialog
from app.window.public_script_new_dialog import Public_script_new_dialog
from app.window.custom_ui.opt_widget import Opt_widget
from database.db import Database
from app.window.del_script_group_dialog import Del_script_group_dialog

class Public_script_manager_signal(QObject):
    open_new_task = Signal()
    remove_task = Signal()
    update_task = Signal()


class Public_script_manager_widget(QWidget):
    
    cur_item: QListWidgetItem = None
    signal = Public_script_manager_signal()
    def __init__(self, parent=None):
        super(Public_script_manager_widget, self).__init__(parent)
        self.ui = Ui_widget_public_scripts_manager()
        self.ui.setupUi(self)
        self.msg = Msg_box(self)
        self.col_names = {}
        self.init_col_names()
        self.init_data()

        self.editor_dialog = Public_script_editor_dialog()
        self.editor_dialog.hide()
        self.editor_dialog.signal.save.connect(self.slot_update_script)
        
        self.new_script_dialog = Public_script_new_dialog()
        self.new_script_dialog.hide()
        self.new_script_dialog.signal.save.connect(self.slot_save_script)
        
        self.del_script_group_dialog = Del_script_group_dialog()
        self.del_script_group_dialog.hide()
        self.del_script_group_dialog.signal.delete_script_group.connect(self.slot_del_group)
        
        
        self.ui.pushButton_new.clicked.connect(self.new_script_dialog.slot_show)
        self.ui.pushButton_auto_size.clicked.connect(self.auto_tab_size)
        self.ui.pushButton_del_group.clicked.connect(self.del_script_group_dialog.slot_show)

        self.auto_tab_size()

    def auto_tab_size(self):
        self.ui.tableWidget.resizeColumnsToContents() #自动列宽
        self.ui.tableWidget.resizeRowsToContents() #自动行高
        # 最后一行自动填充
        self.ui.tableWidget.horizontalHeader().setSectionResizeMode(self.ui.tableWidget.columnCount()-1,QHeaderView.Stretch)
    
    def init_col_names(self):
        # 获取列id
        max_col = self.ui.tableWidget.columnCount()
        for i in range(max_col):
            text = self.ui.tableWidget.horizontalHeaderItem(i).text()
            self.col_names[text] = i


    def new_blank_row(self):
        row_count = self.ui.tableWidget.rowCount()
        self.ui.tableWidget.insertRow(row_count)

        for i in range(self.ui.tableWidget.columnCount()):
            item = QTableWidgetItem('')
            self.ui.tableWidget.setItem(row_count , i, item)
            # 单元格禁止编辑
            self.ui.tableWidget.item(row_count ,i).setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)

            if i == self.col_names['描述']:
                item.setTextAlignment(Qt.AlignLeft | Qt.AlignTop)


    def new_opt_widget(self,script_id:int) -> Opt_widget:
        wid = Opt_widget()

        btn_edit = wid.new_btn('编辑')
        btn_del = wid.new_btn('删除')
        btn_edit.clicked.connect(lambda:self.editor_dialog.slot_show(script_id))
        btn_del.clicked.connect(lambda:self.slot_delete_script(script_id))

        return wid

    
    def init_data(self):
        # 清理现有行 
        row_count = self.ui.tableWidget.rowCount()
        for row in range(row_count,-1,-1):
            self.ui.tableWidget.removeRow(row)
        # 查询公有脚本
        db = Database()
        fields = ['id','name','group_name','info']
        script_list = db.select('scripts',fields,'type="public"')
        for script in script_list:
            self.new_blank_row()
            row = self.ui.tableWidget.rowCount() - 1
            wid = self.new_opt_widget(script[0])
            self.ui.tableWidget.item(row,self.col_names['id']).setText(str(script[0]))
            self.ui.tableWidget.item(row,self.col_names['名称']).setText(script[1])
            self.ui.tableWidget.item(row,self.col_names['分组']).setText(script[2])
            self.ui.tableWidget.item(row,self.col_names['描述']).setText(script[3]) 
            self.ui.tableWidget.setCellWidget(row,self.col_names['操作'],wid)

        db.close_conn()


    def slot_save_script(self,script_id:int):
        # 查询数据
        db = Database()
        script_data = db.select('scripts',['name','group_name','info'],f'id={script_id}')
        data = {
            'name':script_data[0][0],
            'group_name':script_data[0][1],
            'info':script_data[0][2],
        }
        db.close_conn()

        #写入数据
        self.new_blank_row()
        wid = self.new_opt_widget(script_id)
        row = self.ui.tableWidget.rowCount() - 1
        self.ui.tableWidget.item(row,self.col_names['id']).setText(str(script_id))
        self.ui.tableWidget.item(row,self.col_names['名称']).setText(data['name'])
        self.ui.tableWidget.item(row,self.col_names['分组']).setText(data['group_name'])
        self.ui.tableWidget.item(row,self.col_names['描述']).setText(data['info']) 
        self.ui.tableWidget.setCellWidget(row,self.col_names['操作'],wid)


    def slot_update_script(self,script_id:int):
        # 查询数据
        db = Database()
        script_data = db.select('scripts',['name','group_name','info'],f'id={script_id}')
        data = {
            'name':script_data[0][0],
            'group_name':script_data[0][1],
            'info':script_data[0][2],
        }
        db.close_conn()

        
        #更新数据
        for i in range(self.ui.tableWidget.rowCount()):
            if self.ui.tableWidget.item(i,self.col_names['id']).text() == str(script_id):
                self.ui.tableWidget.item(i,self.col_names['名称']).setText(data['name'])
                self.ui.tableWidget.item(i,self.col_names['分组']).setText(data['group_name'])
                self.ui.tableWidget.item(i,self.col_names['描述']).setText(data['info']) 
                break


    def slot_delete_script(self,script_id:int):
        db = Database()
        # 判断计划任务是否存在外键引用
        task_list = db.select('tasks',['id','name'],f'script_id={script_id}')
        if len(task_list) > 0:
            self.msg.msg_tips('计划任务中存在引用.删除对应计划任务后,再尝试')
            for data in task_list:
                print(data[0],data[1])
            db.close_conn()
            return
        
        db.delete('scripts',f'id={script_id}')
        db.close_conn()

        for i in range(self.ui.tableWidget.rowCount()):
            if self.ui.tableWidget.item(i,self.col_names['id']).text() == str(script_id):
                self.ui.tableWidget.removeRow(i)
                break
    

    def slot_del_group(self,group_name:str):
        for i in range(self.ui.tableWidget.rowCount() - 1,-1,-1):
            if self.ui.tableWidget.item(i,self.col_names['分组']).text() == group_name:
                self.ui.tableWidget.removeRow(i)